<!--
 * @Date: 2023-03-27 15:12:12
 * @LastEditTime: 2023-05-05 23:15:41
 * @FilePath: /nlk/src/views/topUpCoin/topUpCoin.vue
 * 介绍:充币
-->

<script lang="ts" setup>
import { PickerColumn, PickerConfirmEventParams, showDialog } from "vant";
import useBalanceStore, { StoreCoinItem } from "@@/store/useBalanceStore";
import { useRpopupRef } from "@@/components/rework/Rpopup";
import { formatNumber, _require } from "@@/utils/tools/tools";
import toast from "@@/hooks/toast";
import { checkAuth } from "@@/hooks/sysHooks";
import topUpCoinLogs from "./components/topUpCoinLogs.vue";
import { apiTopUpAddress } from "@@/api/module/sys";
import { apiTopUpCoinTxid } from "@@/api/module/transaction";
import * as web3Eth from "@@/sdk/web3Eth";

const { t } = useI18n();
const balanceStore = useBalanceStore();
const { coinEnum } = storeToRefs(balanceStore);

const currentCoinKey = ref(Object.keys(coinEnum.value)[0]);
const currentCoin = computed(() => coinEnum.value[currentCoinKey.value]);
watch(
  currentCoinKey,
  () => {
    balanceStore.findBalance(currentCoin.value!);
  },
  { immediate: true }
);
/**picker选择器弹窗 */
const RpopupRef = useRpopupRef();
//*切换coin
function onPickerConfirm(e: PickerConfirmEventParams) {
  const electCoin = e.selectedOptions[0];
  currentCoinKey.value = (electCoin?.value as string).toUpperCase();
  RpopupRef.value?.close();
}
/**picker选择器数据 */
const pickerData = computed<PickerColumn>(() => {
  return Object.values(coinEnum.value).map((v) => ({
    ...v,
    text: v?.code,
    value: v?.code,
  }));
});

const formData = reactive({
  amount: "",
});
function onSubmit() {
  const amount = Number(formData.amount);
  const coin = currentCoin.value!;
  if (!coin.contract_addr) return toast.text(t("zan-bu-zhi-chi-gai-bi-zhong"));
  if (!(amount > 0))
    return toast.text(`${t("bu-neng-xiao-yu")}: 0${coin.code}`);
  checkAuth(coin).then(async () => {
    toast.loading();
    const balance = await balanceStore.findBalance(coin);
    toast.close();
    if (!(amount <= balance!)) return toast.text(t("yu-e-bu-zu"));
    withdrawCoin(coin, amount);
  });
}
/**发起充币 */
async function withdrawCoin(coin: CoinInfo, amount: number) {
  if (!window.isBnb) return toast.text(t("zan-wei-zhi-chi-ci-lian"));
  toast.loading();
  const addressRes = await apiTopUpAddress();
  toast.close();
  if (!addressRes) return toast.error(t("fu-wu-qi-cuo-wu"));
  toast.loading();
  const res = await web3Eth.sdkAutoTransfer(
    coin.contract_addr,
    amount,
    coin.format,
    addressRes.address
  );
  toast.close();
  if (!res.status) return toast.error(res.message || "fail");
  apiTopUpCoinTxid({
    txid: res.data!,
    chainId: 56,
    coin_id: coin.id,
    number: amount,
  });
}
</script>

<template>
  <CpageView class="coinExchange">
    <div class="auto-MT-md">
      <div class="flex-J-SB T-S-sm">
        <div>{{ $t("fa-song") }}</div>
        <div>
          {{ $t("yu-e") }}<span>:</span>
          {{ formatNumber(currentCoin?.balance, 4) }}
        </div>
      </div>
      <Ccard
        @click="RpopupRef?.open()"
        bg="var(--C-B2)"
        class="border-dashed active flex-J-SB flex-A-C"
      >
        <div class="flex-A-C">
          <Rimage height="60rem" width="60rem" :src="currentCoin?.logo" />
          <span class="ML-xs">{{ currentCoin?.code }}</span>
        </div>
        <Ricon r-name="icon-xiajiantou" />
      </Ccard>
      <div class="T-S-sm">
        <div>{{ $t("shu-liang") }}</div>
      </div>
      <Ccard bg="var(--C-B2)" class="border-dashed flex-J-SB flex-A-C">
        <VanField
          v-model="formData.amount"
          :placeholder="$t('chong-bi-shu-liang')"
        >
          <template #extra> {{ currentCoin?.code }}</template>
        </VanField>
      </Ccard>
      <VanButton
        @click="onSubmit"
        class="MT-lg"
        color="var(--C-success)"
        :size="'large'"
        block
      >
        {{ $t("que-ren") }}
      </VanButton>
      <div
        @click="$router.push({ name: 'topUpCoinHelp' })"
        class="topUpCoinHelp T-A-R T-S-sm"
      >
        {{ $t("chong-bi-bu-dao-zhang") }}
      </div>
      <topUpCoinLogs />
    </div>
    <Rpopup ref="RpopupRef" :position="'bottom'">
      <van-picker
        @confirm="onPickerConfirm"
        @cancel="RpopupRef?.close"
        :title="$t('qing-xuan-ze')"
        :columns="pickerData"
      >
        <template #option="{ code, logo }: StoreCoinItem">
          <div class="flex-A-C flex-J-SB" style="width: 5em">
            <Rimage width="1.2em" height="1.2em" :src="logo" />
            <div class="T-A-C" style="width: 3em">{{ code }}</div>
          </div>
        </template>
      </van-picker>
    </Rpopup>
  </CpageView>
</template>

<style lang="less" scoped>
.topUpCoinHelp {
  text-decoration: underline;
}
.border-dashed {
  border: dashed 1rem var(--C-T1);
}
</style>
